﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SalaryChannel.SCQueryService;
using System.Threading;

namespace SalaryChannel
{
    public partial class QueryControl : UserControl
    {
        //static Timer ClickTimer = new Timer(new TimerCallback(SetClickable,Query));
        static DateTime oldTime = DateTime.Now;
        readonly static int QuerySpan = 10;
        public QueryControl()
        {
            InitializeComponent();
            ServiceInstance.QueryClient.QuerySalaryMonByIDCompleted += new EventHandler<QuerySalaryMonByIDCompletedEventArgs>(QueryClient_QuerySalaryMonByIDCompleted);
            ServiceInstance.QueryClient.DeleteAllCompleted += new EventHandler<DeleteAllCompletedEventArgs>(client_DeleteAllCompleted);
            ServiceInstance.QueryClient.GetSalaryPoolCompleted += new EventHandler<GetSalaryPoolCompletedEventArgs>(client_GetSalaryPoolCompleted);
                      
        }     
      
        private bool CanQuery = true;
             
        void QueryControl_Loaded(object sender, RoutedEventArgs e)
        {
            
            
        }
        
        public bool GetStatisMon
        {
            set
            {
                if (value)
                {
                    try
                    {
                        ServiceInstance.QueryClient.GetStatisMonAsync();
                    }
                    catch (Exception)
                    {

                    }
                }
            }
        }


        public void Initialize()
        {
            this.ResultGrid.ItemsSource = null;
            this.SalaryPoolGrid.ItemsSource = null;


         
            this.DeleteAllBtn.Visibility = App.IsAuth(8) ? Visibility.Visible : Visibility.Collapsed;

            // this.ChannelIDLabel.Visibility = Visibility.Visible;
            //this.ChannelIDTB.Visibility = Visibility.Visible;
            this.ChannelIDTB.IsReadOnly = false;
            this.ChannelIDTB.Text = string.Empty;
            if (!App.IsAuth(9))
            {
                this.ChannelIDTB.Text = App.CurrentUser.ChannelID;
                this.ChannelIDTB.IsReadOnly = true;
            }

        }

        void QueryClient_QuerySalaryMonByIDCompleted(object sender, QuerySalaryMonByIDCompletedEventArgs e)
       
        {
            try
            {
                if (e.Result == null)
                {

                    App.MessageBox.ShowDialog("查询酬金失败", Title.Error);
                }
                else
                {
                    Silverlight.DataTable table = Xml2Table.Convert(e.Result.TableNamek__BackingField,
                                  e.Result._columns, e.Result.XmlStringk__BackingField);
                    if (table.Rows.Count == 0)
                    {
                        App.MessageBox.ShowDialog("没有查询到数据");
                        this.ResultGrid.ItemsSource = null;
                        return;
                    }
                    if (e.UserState.ToString() == "ListShow")
                    {

                        this.ResultGrid.ItemsSource = table.GetBindableData(new Silverlight.Connector());
                    }
                    else if (e.UserState.ToString() == "DetailShow")
                    {
                        GenerateDetailShow(table);
                        detailLoading.Stop();

                    }
                    //this.ResultGrid.ItemsSource = e.Result.;
                }
                //this.CountTB.Text = this.ResultGrid.ItemsSource;
            }
            catch 
            {
                App.MessageBox.ShowDialog("查询酬金失败", Title.Error);
            }
            finally
            {
                this.Cursor = Cursors.Arrow;
                CanQuery = true;
                Loading1.Stop();
            }
        }

        void client_GetStatisMonCompleted(object sender, GetStatisMonCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("获取统计月份失败", Title.Error);
                }
                else
                {
                    this.StatisMonCBox.ItemsSource = e.Result;
                    this.StatisMonCBox.SelectedIndex = this.StatisMonCBox.Items.Count - 1;
                }

            }
            catch
            {
                App.MessageBox.ShowDialog("获取统计月份失败", Title.Error);
            }
            finally
            {
                this.Cursor = Cursors.Arrow;
                //this.QueryBtn.IsEnabled = true;
            }
        }

        private void QueryBtn_Click(object sender, RoutedEventArgs e)
        {
            if (!CanQuery)
            {
                return;

            }

            TimeSpan ts = DateTime.Now - oldTime;
            if (App.IsAuth(13)
                || ts.Seconds > QuerySpan)
            {

                if (this.StatisMonCBox.SelectedItem != null)
                {
                    string month =this.StatisMonCBox.SelectedItem.ToString();
                    if (string.IsNullOrEmpty(month))
                    {
                        return;
                    }
                    ServiceInstance.QueryClient.QuerySalaryMonByIDAsync(month , this.ChannelIDTB.Text,App.CurrentUser.UserName,"ListShow");
                    ServiceInstance.QueryClient.GetSalaryPoolAsync(App.CurrentUser.UserID, month, this.ChannelIDTB.Text);
                    CanQuery = false;
                    oldTime = DateTime.Now;
                    this.Cursor = Cursors.Wait;

                    Loading1.Show();
                    Loading2.Show();
                }
                else
                {
                    App.MessageBox.ShowDialog("请先选择查询月份！", Title.Warning);
                
                }
            }
            else
            {
                App.MessageBox.ShowDialog(string.Format("请不要频繁查询!当前查询间隔为{0}秒。", QuerySpan), Title.Warning);
                
            }
        }

        void client_GetSalaryPoolCompleted(object sender, GetSalaryPoolCompletedEventArgs e)
        {
            try
            {
               // this.SalaryPoolGrid.co
                this.SalaryPoolGrid.ItemsSource = e.Result;
                
                //this.CountTB.Text = this.ResultGrid.ItemsSource;
            }
            catch 
            {
                App.MessageBox.ShowDialog("查询酬金池失败", Title.Error);
            }
            finally
            {
                // this.QueryBtn.IsEnabled = true;
                this.Cursor = Cursors.Arrow;
                Loading2.Stop();
            }
        }

        private void DeleteAllAction()
        {
            try
            {
                ServiceInstance.QueryClient.DeleteAllAsync(this.StatisMonCBox.SelectedItem.ToString());
                CanQuery = false;
                this.Cursor = Cursors.Wait;
            }
            catch
            {
                Cursor = Cursors.Arrow; 
                App.MessageBox.ShowDialog(Properties.Resource.ConnectServerFailed, Title.Error);
            }
        }
        private void DeleteAllBtn_Click(object sender, RoutedEventArgs e)
        {
            if (!CanQuery)
            {
                return;
            }
            if (this.StatisMonCBox.SelectedItem != null)
            {
                string msg = string.Format("您将删除统计月份为{0}的所有数据！", this.StatisMonCBox.SelectedItem.ToString());
                App.MessageBox.ShowDialog(msg, new Action(DeleteAllAction), Title.Warning);
                
               
            }
        }

        void client_DeleteAllCompleted(object sender, DeleteAllCompletedEventArgs e)
        {
            
            string msg = string.Empty;
            Cursor = Cursors.Arrow;
            try
            {
                if (e.Result)
                {
                    msg = "全部删除成功";
                    this.ResultGrid.ItemsSource = null;
                    this.SalaryPoolGrid.ItemsSource = null;
                }
                else
                {
                    msg = Properties.Resource.TryAgain;
                }

            }
            catch (Exception ex)
            {
                msg = "服务异常:" + ex.Message;
            }
            finally
            {
                CanQuery = true;
                App.MessageBox.ShowDialog(msg, Title.Information);
            }

        }

        private void GetStatisMonBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ServiceInstance.QueryClient.GetStatisMonCompleted -= client_GetStatisMonCompleted;
            }
            catch 
            {
            }
            try
            {
                ServiceInstance.QueryClient.GetStatisMonCompleted += new EventHandler<GetStatisMonCompletedEventArgs>(client_GetStatisMonCompleted);
                ServiceInstance.QueryClient.GetStatisMonAsync();
                this.Cursor = Cursors.Wait;
            }
            catch 
            {
                this.Cursor = Cursors.Arrow;
                App.MessageBox.ShowDialog(Properties.Resource.ConnectServerFailed, Title.Error);
            }
        }

        /// <summary>
        /// 查看
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TextBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            TextBlock tb = sender as TextBlock;
            if (tb.Tag != null)
            {
                if (this.StatisMonCBox.SelectedItem != null)
                {
                    string month = this.StatisMonCBox.SelectedItem.ToString();
                    if (string.IsNullOrEmpty(month))
                    {
                        return;
                    }
                    try
                    {
                        ServiceInstance.QueryClient.QuerySalaryMonByIDAsync(month, tb.Tag.ToString(), App.CurrentUser.UserName, "DetailShow");
                        ClearDetailShow();
                        DetailShow.Visibility = Visibility.Visible;
                        detailLoading.Show();
                    }
                    catch 
                    {
                        App.MessageBox.ShowDialog("连接服务器失败", Title.Error);
                    }
                }
                else
                {
                    App.MessageBox.ShowDialog("请先选择查询月份！", Title.Warning);

                }
            }
        }

        void ClearDetailShow()
        {
            foreach (UIElement ui in DetailGrid.Children)
            {
                if (ui is TextBlock)
                {
                    TextBlock tb =(ui as TextBlock);
                    if(tb.Tag!=null && tb.Tag.Equals("content")) tb.Text = string.Empty;
                }
            }
        }

        Silverlight.DataTable detailGridColne = null;
        void GenerateDetailShow(Silverlight.DataTable table)
        {
            try
            {
                if (table.Rows.Count != 1)
                {
                    return;
                }
                DetailTitleTB.Text = table.Rows[0]["渠道名称"];

                bool rebulid = false;
                if (detailGridColne == null)
                {
                    rebulid = true;
                }
                else if(detailGridColne.Columns.Count != table.Columns.Count)
                {
                    rebulid = true;
                }
                else 
                {
                    for (int i=0;i<detailGridColne.Columns.Count;i++)
                    {
                        if (detailGridColne.Columns[i].ColumnName != table.Columns[i].ColumnName)
                        {
                            rebulid = true;
                            break;
                        }
                    }
                }
         

                if (rebulid)
                {
                    int columnCount = 6;
                    int TableColCount = table.Columns.Count;
                    int rowCount = (TableColCount - TableColCount /3 * 3) == 0 ? TableColCount /3 : (TableColCount / 3 + 1);

                    DetailGrid.Children.Clear();
                    DetailGrid.ColumnDefinitions.Clear();
                    DetailGrid.RowDefinitions.Clear();


                    for (int i = 0; i < columnCount; i++)
                    {
                        ColumnDefinition col = new ColumnDefinition();
                        if (i == 2)
                        {
                            col.Width = new GridLength(24, GridUnitType.Star);
                        }
                        else if (i % 2 == 0)
                        {
                            col.Width = new GridLength(23, GridUnitType.Star);
                        }
                        else
                        {
                            col.Width = new GridLength(10, GridUnitType.Star);
                        }

                        DetailGrid.ColumnDefinitions.Add(col);
                    }
                    for (int i = 0; i < rowCount; i++)
                    {
                        RowDefinition rd = new RowDefinition();
                        rd.Height = new GridLength(30);
                        DetailGrid.RowDefinitions.Add(rd);
                    }

                    for (int i = 4; i < table.Columns.Count; i++)
                    {
                        int colIndex = (i-4) * 2 % DetailGrid.ColumnDefinitions.Count;
                        int rowIndex = (i-4) / (DetailGrid.ColumnDefinitions.Count/2);

                        TextBlock title = new TextBlock();
                        title.HorizontalAlignment = HorizontalAlignment.Center;
                        title.VerticalAlignment = VerticalAlignment.Center;
                        title.FontSize = 13;
                        title.Text = table.Columns[i].ColumnName ;
                        title.SetValue(Grid.RowProperty, rowIndex);
                        title.SetValue(Grid.ColumnProperty, colIndex);
                        title.Tag = "title";

                        TextBlock content = new TextBlock();
                        content.HorizontalAlignment = HorizontalAlignment.Center;
                        content.VerticalAlignment = VerticalAlignment.Center;
                        content.FontSize = 13;
                        content.Text = table.Rows[0][i];
                        content.SetValue(Grid.RowProperty, rowIndex);
                        content.SetValue(Grid.ColumnProperty, colIndex + 1);
                        content.Tag = "content";

                        DetailGrid.Children.Add(title);
                        DetailGrid.Children.Add(content);
                    }

                    detailGridColne = table.Clone(false);
                }
                else
                {
                    for (int i = 0; i < DetailGrid.Children.Count;i++ )
                    {
                        if (DetailGrid.Children[i] is TextBlock)
                        {
                            TextBlock tb = (DetailGrid.Children[i] as TextBlock);
                            if (tb.Tag != null && tb.Tag.Equals("content"))
                            {
                                tb.Text = table.Rows[0][i/2+4];
                            }
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                App.MessageBox.ShowDialog("解析数据失败，" + ex.Message);
            }

        }

        private void BackBtn_Click(object sender, RoutedEventArgs e)
        {
            DetailShow.Visibility = Visibility.Collapsed;
        }


    }
}
